using System;
using System.Globalization;
using System.Linq;
using System.Windows.Data;

namespace WPFTemplateLib.WpfConverters
{
	/// <summary>
	/// [转换器] 绑定内容的字符串形式作为 Key 在参数中查找 Value 字符串（参数以 | 分组，组内以 , 或 : 分隔出 key 和 value）
	/// </summary>
	/// <example>
	///	<![CDATA[
	/// Converter={StaticResource BindAsKeyFindValueInParaConverter}
	/// 转换器参数示例：
	///	ConverterParameter='Show,浏览 | Edit,编辑 | Add,添加'
	/// ConverterParameter='0:开始 | 1:起步 | 2:加速 | 3:冲锋 | 4:减速 | 5:停止'
	/// ]]>
	/// </example>
	public class BindAsKeyFindValueInParaConverter : IValueConverter
	{
		/// <inheritdoc />
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			string logPrefix = nameof(BindAsKeyFindValueInParaConverter);
			try
			{
				string valueStr = value + "";
				string paraStr = parameter + "";
				var candidateList = paraStr.Split('|').ToList(); // KeyValuePair 以 "|" 分隔;
				if(string.IsNullOrWhiteSpace(paraStr))
				{
					Console.WriteLine($"[{logPrefix}]缺少参数");
					return valueStr;
				}

				char pairSeparator;
				if(paraStr.Contains(","))
				{
					pairSeparator = ',';
				}
				else if(paraStr.Contains(":"))
				{
					pairSeparator = ':';
				}
				else
				{
					Console.WriteLine($"[{logPrefix}]缺少 Key、Value 之间的分隔符");
					return valueStr;
				}

				foreach(string keyValuePairStr in candidateList)
				{
					var pair = keyValuePairStr.Split(new[] { pairSeparator }, StringSplitOptions.RemoveEmptyEntries);
					if(pair.Length < 2)
						continue;

					if(value + "" == pair[0].Trim())
					{
						return pair[1].Trim();
					}
				}

				return valueStr;
			}
			catch(Exception ex)
			{
				Console.WriteLine($"[{logPrefix}]发生异常：{ex}");
				return string.Empty;
			}
		}

		/// <inheritdoc />
		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			throw new NotImplementedException();
		}
	}
}
